package com.example.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.UserDto;
import com.example.springboot.controller.dto.UserPasswordDto;
import com.example.springboot.entity.Menu;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.RoleMapper;
import com.example.springboot.mapper.RoleMenuMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luo
 * @since 2023-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuServiceImpl menuService;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    private static final Log LOG= Log.get();
    @Override
    public UserDto login(UserDto userDto) {
        User one = getUserInfo(userDto);
        if (one!=null){
            BeanUtil.copyProperties(one,userDto,true);
            //设置token
            String s = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDto.setToken(s);

            String role = one.getRole();
            List<Menu>roleMenus=getRoleMenus(role);
            //设置用户的菜单列表
            userDto.setMenus(roleMenus);
            return userDto;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public User rejister(UserDto userDto) {
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("username",userDto.getUsername());
        User one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (one==null){
            one=new User();
            BeanUtil.copyProperties(userDto,one,true);
            one.setRole("ROLE_USER");
            save(one);
        }else {
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }

    @Override
    public void updatePassword(UserPasswordDto userPasswordDto) {
        int update = userMapper.updatePassword(userPasswordDto);
        if (update<1){
            throw new ServiceException(Constants.CODE_600,"原密码错误");
        }
    }

    private User getUserInfo(UserDto userDto){
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("username",userDto.getUsername());
        queryWrapper.eq("password",userDto.getPassword());
        User one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param role
     * @return
     */
    private List<Menu> getRoleMenus(String role){
        final Integer roleId = roleMapper.selectByFlag(role);
        List<Integer> menuIds=roleMenuMapper.selectByRoleId(roleId);
        //查出系统所有的菜单
        final List<Menu> menus = menuService.findMenus("");
        //最后筛选完的list
        List<Menu>roleMenus=new ArrayList<>();
        //筛选当前用户角色菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())){
                roleMenus.add(menu);
            }
            final List<Menu> children = menu.getChildren();
            // removeIf() 移除children 里面不在 menuIds集合的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
